//
//  OAuthViewController.swift
//  AsiaWeiBo
//
//  Created by 史亚洲 on 16/1/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: UIViewController    {
    
    //属性webView
    let webView = UIWebView()
    
    //关闭页面
    @objc private func close() {
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    //自动填充账号
    @objc private func defaultAccount() {
    
        let jsonString = "document.getElementById('userId').value = '15896976173',document.getElementById('passwd').value = 'Asia199322'"
    
    webView.stringByEvaluatingJavaScriptFromString(jsonString)
    
    }


    override func loadView() {
        //将根视图设置为webView
        view = webView
        //设置代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        oauth()
    }
    
    //2.设置导航条
    func setNavBar(){
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }

    //1.请求授权
    func oauth() {
        /*//请求
        https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
        App Key：537801178
        App Secret：d08baaa3e32c963fec3703808cc32e05
        授权回调页：http://www.itcast.com
        */
        //1.获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
         let url = NSURL(string: urlString)!
         let request = NSURLRequest(URL: url)
           
            //print(request)
       webView.loadRequest(request)
    
    }

    

}

//扩展,设置协议,便于阅读和维护
extension OAuthViewController: UIWebViewDelegate {

    //1.显示用户等待信息
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //2.关闭用户等待信息
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    //1.webView的协议方法,返回值为true,表示控件可以正常运行,获取code授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print(request)
        guard let urlString = request.URL?.absoluteString else {
        
        return false
        
        }
        
        if urlString.containsString("code=") {
        
        print(urlString)
            guard let query = request.URL?.query else {
            
            return false
            
            }
            let codeStr = "code="
            
            //将query转化为NSString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code,query)
   
            //调用获取token的方法
            loadAccessToken(code)
            
            
            //不让页面跳转到回调页面
            return false
        }
        
        
        return true
    }
    
    private func loadAccessToken(code: String) {
    
    //请求token和用户信息
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess{
            print("用户登录失败")
            SVProgressHUD.showErrorWithStatus("网络君正在睡觉,请稍后再试")
                return
            
            
            }
            
            //一定登录成功
            SVProgressHUD.showInfoWithStatus("登录成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    
    }

}
